#include <iostream>
#include <SFML/Graphics.hpp>
#include "../../include/Engine.hpp"
#include "../../include/GUI/Checkbox.hpp"

namespace GUI
{

    Checkbox::Checkbox(Engine &Moteur, const sf::String &text) : Widget(Moteur)
    {
        m_image.SetImage(*m_Moteur.Graphic()->GetGUIImage(6)); // On charge l'image de la checkbox

        m_rects.push_back(sf::IntRect(0,0,18,18)); // Non checker
        m_rects.push_back(sf::IntRect(18,0,18,18)); // Checker

        m_dimensions.height = 18;
        m_dimensions.width = 180;

        SetText(text);

        m_ishover = false;
        m_ischeck = false; // La checkbox n'est pas "checker" par defaut

        // Sons
        m_buffer.LoadFromFile("Musics/Sounds/Bouton.wav");
        m_son.SetBuffer(m_buffer);

        m_shape = sf::Shape::Rectangle(m_position.x, m_position.y, m_dimensions.width, m_dimensions.height, sf::Color(40,40,40,30));

        m_text.SetCharacterSize(14);
        m_text.SetColor(m_Moteur.Config()->GetGUI()->color_contenu);
    }

    bool Checkbox::IsCheck()
    {
        return m_ischeck;
    }
    void Checkbox::SetCheck(bool check)
    {
        m_ischeck = check;
    }

    bool Checkbox::IsHover()
    {
        int x = m_Moteur.App().GetInput().GetMouseX();
        int y = m_Moteur.App().GetInput().GetMouseY();
        int hauteur = 0;
        int largeur = 0;

        if(m_parent != NULL)
            largeur = m_parent->GetDimensions().width-m_padding-(GetPosition().x-m_parent->GetPosition().x);
        else
            largeur = m_text.GetRect().Width;

        hauteur = m_dimensions.height;

        if(x > m_position.x and y > m_position.y and x < m_position.x+largeur+2*m_padding and y < m_position.y+hauteur)
            return true;
        else
            return false;
    }

    void Checkbox::SetText(const sf::String &text)
    {
        m_text.SetString(text);

        m_dimensions.width = 18 + m_padding + m_text.GetRect().Width;
        m_dimensions.height = 18;
    }

    void Checkbox::Afficher()
    {
        if(m_ishover)
        {
            float x = 0;

            if(m_parent != NULL)
            {
                x = (m_parent->GetDimensions().width-m_conteneur_position.x)/(m_dimensions.width);
            }

            m_shape.SetPosition(m_position.x, m_position.y);
            m_shape.SetScaleX(x);
            m_Moteur.Graphic()->Draw(m_shape);
        }

        if(IsCheck())
            m_image.SetSubRect(m_rects[1]);
        else
            m_image.SetSubRect(m_rects[0]);

        m_image.SetPosition(m_position.x, m_position.y);
        m_text.SetPosition(m_position.x+m_padding+18, m_position.y);

        m_Moteur.Graphic()->Draw(m_image);
        m_Moteur.Graphic()->Draw(m_text);
    }
    void Checkbox::UpdateEvent()
    {
        m_ishover = IsHover();

        if(IsClicked())
        {
            m_son.Play();

            if(IsCheck())
                m_ischeck = false;
            else
                m_ischeck = true;
        }
    }

}
